package com.kim.rssreader.activity;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import cn.waps.AppConnect;

import com.kim.rssreader.R;
import com.kim.rssreader.domain.constant.Contant;
import com.kim.rssreader.service.RssColumnUpdateService;
import com.kim.rssreader.service.StarterImageFetchService;
import com.kim.rssreader.utils.LocationUtil;
import com.kim.rssreader.utils.LocationUtil.LocationCallback;
import com.kim.rssreader.utils.NetUtil;
import com.kim.rssreader.utils.NetUtil.NetProcessComplete;
import com.kim.rssreader.utils.StarterImageFetchUtils;
import com.kim.rssreader.utils.ValueConstant;
import com.kim.rssreader.utils.WeatherUtil;

public class StarterActivity extends BaseActivity implements ViewFactory,
		OnGestureListener {

	private static final long HORIZONTAL_FLING_THRESHOLD = 100l;

	public static StarterActivity starterActivity = null;

	private static final int[] imags = new int[] { R.drawable.p1 /*
																 * ,
																 * R.drawable.p2
																 * ,
																 * R.drawable.p3
																 */};

	// String url = "http://api.liqwei.com/weather/?city=%C9%EE%DB%DA";//还没找到接口
	String baseurl = "http://m.weather.com.cn/data/101280601.html";// 深圳
	String url = "http://m.weather.com.cn/data/citycode.html";
	// (返回XML):
	// http://www.yodao.com/smartresult-xml/search.s?type=zip&q=邮编或区号或城市名
	// (返回XML):
	// http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0
	// (返回JSON):http://m.weather.com.cn/data/101280601.html 要中国天气城市代码

	String city = ""; // 城市
	String[] citygroup;
	String date_y = "";// 日期
	String week = "";// 星期

	String temp1 = "";//
	String temp2 = "";//
	String temp3 = "";//
	String temp4 = "";//
	String temp5 = "";//
	String temp6 = "";//

	String weather1 = "";//
	String weather2 = "";//
	String weather3 = "";//
	String weather4 = "";//
	String weather5 = "";//
	String weather6 = "";//

	String wind1 = "";//
	String wind2 = "";//
	String wind3 = "";//
	String wind4 = "";//
	String wind5 = "";//
	String wind6 = "";//

	String img1 = "";

	private TextView txv_city;
	private TextView txv_weather;;
	private TextView txv_date;
	private TextView txv_week;
	private TextView txv_temp;;
	private ImageView img_weatherPic;
	private TextView txv_wind;

	private int currentIndex;

	ImageSwitcher imageSwitcher;
	ImageView imageView;

	Bitmap bitmap;

	private GestureDetector gestureDetector;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ValueConstant.MSG_IMAGE_REFRESH:
				imageSwitch();
				handler.sendEmptyMessageDelayed(
						ValueConstant.MSG_IMAGE_REFRESH, 3000);
				break;
			case Contant.GET_WEATHER_PIC_SUCCESS:
				img_weatherPic.setImageBitmap(bitmap);
				break;
			case Contant.GET_LOCATION_SUCCESS:
				packageWeatherUrl();
				getWeatherData();
				break;
			case Contant.GET_WEATHER_DATA_SUCCESS:
				String phoneInfo = (String) msg.obj;
				if (phoneInfo != null) {
					phoneInfo = phoneInfo.replace("{\"weatherinfo\":", "");
					phoneInfo = phoneInfo.substring(0, phoneInfo.length() - 1);
					analysisJSON(phoneInfo);
				}
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 万普统计
		AppConnect.getInstance(this);

		starterActivity = this;

		checkLocation();// 定位用户位置

		// 获取天气数据
		startRssColumnUpdate();
		startFecthImage();
		loadImageDrawable();

		gestureDetector = new GestureDetector(this);
	}

	// 定位用户位置
	private void checkLocation() {
		LocationUtil locationUtil = new LocationUtil(this,
				new LocationCallback() {
					@Override
					public void onLocateSuccess(String[] result) {
						Looper.prepare();
						citygroup = result;
						handler.sendEmptyMessage(Contant.GET_LOCATION_SUCCESS);
						Looper.loop();
					}
				});
		locationUtil.updateLocation();
	}

	@Override
	public void initParam() {

	}

	@Override
	public void initView() {
		setContentView(R.layout.starter_activity);
		txv_city = (TextView) findViewById(R.id.weather_txv_city);
		txv_weather = (TextView) findViewById(R.id.weather_txv_weather);
		txv_date = (TextView) findViewById(R.id.weather_txv_date);
		txv_week = (TextView) findViewById(R.id.weather_txv_week);
		txv_temp = (TextView) findViewById(R.id.weather_txv_temp);
		txv_wind = (TextView) findViewById(R.id.weather_txv_wind);
		img_weatherPic = (ImageView) findViewById(R.id.weather_img_pic);
		imageView = (ImageView) findViewById(R.id.img_toMain);
		imageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				toMainActivity();
			}
		});
		imageSwitcher = (ImageSwitcher) findViewById(R.id.imgSwitcher);
		imageSwitcher.setFactory(this);
		imageSwitcher.setImageResource(R.drawable.p1);
		currentIndex = 0;
		handler.sendEmptyMessage(ValueConstant.MSG_IMAGE_REFRESH);

		getWeatherDataFromShare();
		showWeather();
	}

	/**
	 * 跳转到首页
	 */
	private void toMainActivity() {
		Intent intent = new Intent(this, MainActivity2.class);
		startActivity(intent);
	}

	private void imageSwitch() {
		currentIndex++;
		int index = 0;
		if (drawableArray != null && drawableArray.length > 0) {
			index = currentIndex % drawableArray.length;
			imageSwitcher.setImageDrawable(drawableArray[index]);
		} else {
			index = currentIndex % imags.length;
			imageSwitcher.setImageResource(imags[index]);
		}
		currentIndex = index;
	}

	@Override
	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_XY);// 设置全屏
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return i;
	}

	@Override
	protected void onDestroy() {
		// 万普统计
		AppConnect.getInstance(this).finalize();
		super.onDestroy();
	}

	// json解析(解析天气数据）
	private void analysisJSON(String jsonStr) {
		try {
			JSONObject json = new JSONObject(jsonStr);
			city = json.getString("city");
			date_y = json.getString("date_y");
			week = json.getString("week");
			temp1 = json.getString("temp1");
			weather1 = json.getString("weather1");
			wind1 = json.getString("wind1");
			img1 = json.getString("img1");

			saveWeatherDataToShare();// 将天气数据存到Preferences
			showWeather();

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 显示天气数据
	 */
	private void showWeather() {
		txv_city.setText(city);
		txv_weather.setText(weather1);
		txv_date.setText(date_y);
		txv_week.setText(week);
		txv_temp.setText(temp1);
		txv_wind.setText(wind1);
		getWeatherPic();// 获取天气图片
	}

	/**
	 * 获取天气图片
	 */
	private void getWeatherPic() {
		final String weatherPicURL1 = "http://www.weather.com.cn/m/i/icon_weather/42x30/d0"
				+ img1 + ".gif";
		final String weatherPicURL2 = "http://www.weather.com.cn/m/i/icon_weather/42x30/d"
				+ img1 + ".gif";

		// img_weatherPic.setBackgroundResource(R.drawable.weather_cloudy);
		new Thread() {
			public void run() {
				if (img1.length() == 1) {
					bitmap = WeatherUtil.returnBitMap(weatherPicURL1);
				} else if (img1.length() == 2) {
					bitmap = WeatherUtil.returnBitMap(weatherPicURL2);
				}

				Message msg = new Message();
				msg.what = Contant.GET_WEATHER_PIC_SUCCESS;
				handler.sendMessage(msg);
			};
		}.start();
	}

	/**
	 * 开启引导页图片抓取服务
	 */
	private void startFecthImage() {
		Intent service = new Intent(StarterImageFetchService.ACTION_FETCH);
		startService(service);
	}

	/**
	 * 开启rss栏目更新服务
	 */
	private void startRssColumnUpdate() {
		Intent service = new Intent(RssColumnUpdateService.ACTION_FETCH);
		startService(service);
	}

	Drawable[] drawableArray;

	/**
	 * 加载引导页新图片
	 */
	private void loadImageDrawable() {
		drawableArray = StarterImageFetchUtils.loadImage(this,
				StarterImageFetchUtils.getLocalImageVersion(this));
	}

	/**
	 * 组装天气url
	 */
	private void packageWeatherUrl() {
		String country = citygroup[0];
		String town = citygroup[1];
		String citycode = dbDAO.getWeather(country);// 查询
		if (citycode == null || citycode.equals("")) {
			country = citycode.replace("县", "");
			citycode = dbDAO.getWeather(country);
			if (citycode == null || citycode.equals("")) {
				town = town.replace("市", "");
				citycode = dbDAO.getWeather(town);
			}
		}

		if (citycode != null || !(citycode.equals(""))) {
			url = url.replace("citycode", citycode);
		} else {
			url = baseurl;
		}
	}

	/**
	 * 获取天气
	 */
	private void getWeatherData() {
		new Thread() {
			public void run() {
				NetUtil.getInputStream(url, new NetProcessComplete() {

					@Override
					public void onProcess(InputStream inputStream) {
						String result = null;
						try {
							result = NetUtil.convertInputStream2String(
									inputStream, "UTF-8");
						} catch (IOException e) {
							e.printStackTrace();
						}// 查询天气
						Message msg = new Message();
						msg.what = Contant.GET_WEATHER_DATA_SUCCESS;
						msg.obj = result;
						handler.sendMessage(msg);
					}
				});
			};
		}.start();
	}

	/**
	 * 保存天气数据到preferences
	 */
	private void saveWeatherDataToShare() {
		SharedPreferences pref = getSharedPreferences("weather", 0);
		Editor editor = pref.edit();
		editor.putString("city", city);
		editor.putString("date", date_y);
		editor.putString("week", week);
		editor.putString("img", img1);
		editor.putString("weather", weather1);
		editor.putString("temp", temp1);
		editor.putString("wind", wind1);
		editor.commit();
	}

	/**
	 * 从preferences读取保存的天气数据
	 */
	private void getWeatherDataFromShare() {
		SharedPreferences pref = getSharedPreferences("weather", 0);
		city = pref.getString("city", "");
		date_y = pref.getString("date", "");
		week = pref.getString("week", "");
		img1 = pref.getString("img", "");
		weather1 = pref.getString("weather", "");
		temp1 = pref.getString("temp", "");
		wind1 = pref.getString("wind", "");
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		int distanceX = Math.abs((int) e2.getX() - (int) e1.getX());
		int distanceY = Math.abs((int) e2.getY() - (int) e1.getY());
		if (distanceX < HORIZONTAL_FLING_THRESHOLD || distanceX < distanceY) {
			// 限制滑动角度，当 distanceX < distanceY时
			// ，就证明角度太大，可以归并为是垂直滑动不是水平滑动
			return false;
		}
		toMainActivity();
		return true;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		super.dispatchTouchEvent(ev);// 事件传递给系统
		return gestureDetector.onTouchEvent(ev);// 在此就调用手势事件
	}

}
